#include "cc_file.h"
#include <windows.h>

int __cdecl cc_mkdir(
	const char *path
	)
{
	int ret = CreateDirectoryA(path, NULL);
	return (ret ? 0 : -1);
}

int __cdecl cc_rmdir(
	const char *path
	)
{
	int ret = RemoveDirectoryA(path);
	return (ret ? 0 : -1);
}

int __cdecl cc_rename(
	const char *srcName,
	const char *destName
	)
{
	int ret = MoveFileA(srcName, destName);
	return (ret ? 0 : -1);
}

int __cdecl cc_remove(
	const char *fileName
	)
{
	int ret = DeleteFileA(fileName);
	return (ret ? 0 : -1);
}

int __cdecl cc_getFileSize( 
	const char *fileName 
	)
{
	FILE *file = fopen(fileName, "rb");
	int currPos;
	int lastPos;

	if(file == NULL)
	{
		return -1;
	}

	currPos = ftell(file);
	fseek(file, 0, SEEK_END);
	lastPos = ftell(file);
	fseek(file, currPos, SEEK_SET);		// reset the file seek position
	fclose(file);
	return lastPos;
}

void __cdecl cc_readFileToBuf(
	const char	*fileName,
	char	    *buf,
	int			*error
	)
{
	int size = cc_getFileSize(fileName);
	FILE *file;
	int readLen = 0;
	char *tempBuf = buf;
	int freadBufSize = 4 * KB;

	*error = 0;
	if(size < 0)
	{
		*error = 1;
		return;
	}

	file = fopen(fileName, "rb");
	if(file == NULL)
	{
		*error = 1;
		return;
	}

	while(readLen < size)
	{
		int len = fread(tempBuf, sizeof(char), freadBufSize, file);
		if(ferror(file))
		{
			*error = 1;
			break;
		}
		if(len == 0)
		{
			if(!feof(file))
				freadBufSize = size - readLen;	// avoid that the rest of file data size is less than default freadBufSize, fread returns 0.
			else
				break;
		}
		readLen += len;
		tempBuf += len;
	}
	fclose(file);
}
